package com.esint.spring_cloud_leaning.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @description: 自定义过滤器类
 * 需要继承并实现globalfilter和ordered接口
 * @author: 谷明
 * @createDate: 2021/8/8 8:00
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("执行了自定义的全局过滤器");

        //#region 简单模拟token校验

        //1. 获取token
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        //2. 判断是否合法
        if(token == null){
            //3. 如果不合法则返回
            System.out.println("token验证不通过");
            exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
            return exchange.getResponse().setComplete();
        }
        System.out.println("token校验通过");
        //4. 如果合法，则向下执行，请求对应服务

        //#endregion

        return chain.filter(exchange); //继续向下执行
    }

    /**
     * 控制执行顺序， 返回值越小， 优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
